package com.zkjl.protect_business.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.zkjl.protect_business.entity.Business;
import com.zkjl.protect_business.service.BusinessService;
import com.zkjl.protect_business.service.RedisService;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.zkjl.protect_business.common.Consts.INDEX_PREFIX;
import static com.zkjl.protect_business.common.Consts.REDIS_PREFIX;

@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    BusinessService businessService;

    @Override
    public String getbusinessName(String key) {

        String str = stringRedisTemplate.opsForValue().get(REDIS_PREFIX + key);

        //没获取到就全部刷新一下
        if (StringUtils.isBlank(str)) {
            List<Business> businesses = businessService.list();
            businesses.stream().forEach(business -> {

                String name = business.getName();
                String pname = business.getPname();
                String pinyin = PinyinUtil.getPinyin(name, "");
                String ppinyin = "";
                if (StringUtils.isNotBlank(pname)) {
                    ppinyin = PinyinUtil.getPinyin(pname, "");
                }
                stringRedisTemplate.opsForValue().set(REDIS_PREFIX + INDEX_PREFIX + ppinyin + "_" + pinyin, name, 10000, TimeUnit.SECONDS);
            });

            str = stringRedisTemplate.opsForValue().get(REDIS_PREFIX + key);
            return str;
        } else {
            return str;
        }

    }
}
